<?php

namespace app\common\service;

use app\common\service\Base;
use mes\Mes;
class Sku extends Base
{

	/**
	 * 根据sku获取产品详情
	 *
	 * @author KING
	 * @date 2020年7月1日
	 *
	 * @param string $skus
	 * @param string $field
	 * @return array
	 */
	public function getListBySkus($skus, $field='*') {
		if (empty($skus)) return [];
		$skuDataList=db('sku')->where('sku', 'in', $skus)->field($field)->column($field, 'sku');
		foreach($skuDataList as $skuKey=>&$skuinfo){
            $skuinfo['ori_pic']=str_replace('https://www.020mes.com/platform/order/pic/convert?url=','',$skuinfo['ori_pic']);
            $skuinfo['pic']=str_replace('https://www.020mes.com/platform/order/pic/convert?url=','',$skuinfo['pic']);
        }
        return $skuDataList;
	}

	/**
	 * 根据sku获取产品详情
	 *
	 * @author KING
	 * @date 2020年7月1日
	 *
	 * @param string $sku
	 * @param string $field
	 * @return array
	 */
	public function getInfoBySku($sku, $field='*') {
		if (empty($sku)) return [];
		return db('sku')->where('sku', $sku)->field($field)->findOrEmpty();
	}

	/**
	 * 获取SKU图片
	 *
	 * @author KING
	 * @date 2020年7月22日
	 *
	 * @param string $sku
	 * @param bool $isOri	是否原始图
	 * @return string
	 */
	public function getPicBySku($sku, $isOri=true) {
		if ($isOri) $data = cache(SKU_ORI_PIC.$sku);
		else $data = cache(SKU_PIC.$sku);
		if (!empty($data)) return $data;
		return $this->updatePicCache($sku, $isOri);
	}

	/**
	 * 更新SKU图片
	 *
	 * @author KING
	 * @date 2020年7月22日
	 *
	 * @param string $sku
	 * @param bool $isOri	是否原始图
	 * @return string
	 */
	public function updatePicCache($sku, $isOri=true) {
		$skuInfo = db('sku')->where('sku', $sku)->field('pic,ori_pic')->findOrEmpty();
		if ($skuInfo) {
			if($skuInfo['pic']) cache(SKU_PIC.$sku, $skuInfo['pic']);
			if($skuInfo['ori_pic']) cache(SKU_ORI_PIC.$sku, $skuInfo['ori_pic']);
			if($isOri) return $skuInfo['ori_pic'];
			else return $skuInfo['pic'];
		} else return '';
	}

    /**
     * 新增加库存-> 更新至mes（单尺码）
     * @param string $sku
     * @author: huanghuixiang
     * @date: 2022/10/7 16:54
     */
    public function skuStockUptoMesV2($postParm){

        $where[]=['sku','=',$postParm['sku']];
        $where[]=['size_name','=',$postParm['size_name']];
        $mes_count=db("sku_stock_mes")->field('mes_count')->where($where)->find();
        $localStockNum=db('sku_stock')->field('sum(available_count) as total_num')->where($where)->group("size_name")->find();
        $mesNum=empty($mes_count['mes_count'])?0:$mes_count['mes_count'];//mes数
        $localNum=empty($localStockNum['total_num'])?0:$localStockNum['total_num'];//本地库存数

        $addTailNum=$localNum-$mesNum;//本地是否大于mes的
        $addTailStocks[]=['size'=>$postParm['size_name'],'quantity'=>$postParm['addNum']];
        $postdata = [
            'produceOrderId' => $postParm['client_ordernum'],'sizeInfo' => $addTailStocks,
        ];
        //如 本地库存数 < mes库存数 的无需更新
        if($addTailNum< 0){
            $ret=['code'=>1,'msg'=>'没有增数库存，无需更新','addStocks'=>$postdata];
            return $ret;
        }
        $mesLib = new Mes();
        $result = $mesLib->upMesTailStock($postdata);
        //成功
        if($result['code']==0){
            //更新mes同步表的库存
            db("sku_stock_mes")->where($where)->update(['mes_count'=>$mesNum+$postParm['addNum']]);
        }
        $msg=$result['code']==0 ? "扫码入库-新增库存到mes: 增加".$postParm['addNum'].'件，尺码:'.$postParm['size_name'].'，sku:'.$postParm['sku'] : $result['msg'];
        return ['code'=>0,'msg'=>$msg,'addStocks'=>$postdata,'mesApiRet'=>$result];
    }

    //成衣库存更新至mes
    public function skuStockUptoMes($sku){
        $sku_stocklist=db("sku_stock")->where([['sku','=',$sku],['available_count','>',0]])
            ->field("sku,size_name,available_count,sum(available_count) as size_count,defective_count,sum(defective_count) as defective_size_count,
                    stock_position,factory_id,defective_reason,client_ordernum")->group('sku,size_name')->order("update_time desc")->select();
        $localStockArr=array_column($sku_stocklist,'available_count','size_name');
        $mes_stock=db("sku_stock_mes")->where([['sku','=',$sku]])->find();
        //获取mes平台库存键值对
        $mesStockArr=empty($mes_stock['mes_detail']) ? [] : $this->getArrybyStockString($mes_stock['mes_detail']);
        $addTailStocks=[];//要提交新增的库存
        foreach ($localStockArr as $sizeName=>$localStockNum){
            $mesStockArr[$sizeName]=empty($mesStockArr[$sizeName]) ? 0 : $mesStockArr[$sizeName];
            $addNumber=$localStockNum-$mesStockArr[$sizeName];
            if($addNumber>0){ //线上该尺码尾数少于本地
                $addTailStocks[]=['size'=>$sizeName,'quantity'=>$addNumber];
                $mesStockArr[$sizeName]+=$addNumber;
            }
        }
        $postdata = [
            'produceOrderId' => $sku_stocklist[0]['client_ordernum'],'sizeInfo' => $addTailStocks,
        ];
        if(count($addTailStocks)<=0){
            $ret=['code'=>1,'msg'=>'没有增数库存，无需更新','addStocks'=>$postdata];
            return $ret;
        }

        $mesLib = new Mes();
        $result = $mesLib->upMesTailStock($postdata);
        //0为成功，将更新后的尺码库存更新至本地mes尾数，以防重复更新
        if($result['code']==0){
            $stockdstrs='';
            foreach ($mesStockArr as $sizename=>$stockval){
                $stockdstrs.=$sizename.":".$stockval."<br/>";
            }
            //更新推送mes尾货数 成功
            db("sku_stock_mes")->where([['sku','=',$sku]])->update(['mes_detail'=>trim($stockdstrs,"<br/>")]);
        }
        $msg=$result['code']==0 ? "增数已更新至mes" : $result['msg'];
        return ['code'=>0,'msg'=>$msg,'addStocks'=>$postdata,'mesApiRet'=>$result];

    }


    //库存字段转数组
    public function getArrybyStockString($stockstring){
	    //1XL:0<br/>3XL:3<br/>4XL:0
        $stockstring=explode("<br/>",$stockstring);
        $newArr=[];
        foreach ($stockstring as $key=>$value){
            @list($key, $stockNum)=explode(":",$value);
            @$newArr[$key]=$stockNum;
        }
        return $newArr;
    }

    /**
     * 获取sku成衣库存
     * @author sparkguo
     * 2021-09-01
     */
	public function getSkuStockBySku($sku,$factory_id=0){
        if (empty($sku)) return [];
        $where=['sku'=>$sku];
        if($factory_id>0){
            $where['factory_id']=$factory_id;
        }
        return db('sku_stock')->where($where)->field('size_name,sum(available_count) as available_count,sum(defective_count) as defective_count')->group("size_name")->select();
    }

    public function _get_xm_select_data()
    {
        $res = [];
        $list = db('size')->order('num asc,id asc')->select();
        foreach ($list as $k => $v) {
            $res[] = [
                'name' => $v['name'],
                'value' => $v['id'],
                'data-option' => $v['num'],
                'data-order' => $k,
            ];
        }
        return $res;
    }
}